<?php
namespace Modules\Admin\Model\Service;

use Modules\Admin\Model\Dao\Db\User\User as DbUser;
use Modules\Admin\Model\Data\User as DataUser;
use Base\Exception\Service as Exception;
use Api\SA\Otp;
use Api\SA\Ldap;

class User {

    /**
     * 验证账号密码
     *
     * @param string $username 用户名
     * @param string $password 密码
     *
     * @return array
     * @throws Exception
     * @throws \Exception
     */
    public function loginVerify($username, $password) {
        $user_info = (new DataUser())->getUserInfoByName($username);
        if (!$user_info) {
            throw new Exception('error.admin.login_error');
        }
        if ($user_info['status']) {
            throw new Exception('error.admin.banned_from');
        }

        if ($user_info['password'] == DbUser::PASSWORD_LDAP) {
            $code = substr($password, -6);
            if (!$code) {
                throw new Exception('error.admin.code_error');
            }
            (new Otp())->verify($username, $code);

            $password = substr($password, 0, -6);
            (new Ldap())->login($username, $password);
        } else {
            if ($user_info['password'] !== sha1(sha1($password) . $user_info['salt'])) {
                throw new Exception('error.admin.login_error');
            }
        }

        return $user_info;
    }

}
